import sys,xlrd
from collections import defaultdict
from openpyxl import load_workbook, Workbook

def dealname(name):
    newname = ' '.join(name.split('_')[2:])
    return newname

def dealkk(inputdir,hmd,outputdir):
    stat = defaultdict(int)
    sample = ''
    with open(f'{inputdir}/runStat.xls',encoding='gbk') as f:
        for l in f:
            if l.startswith('NC') and l.find('-D') > -1:
                sample = l.split('\t')[0]
                stat[sample] = int(l.split('\t')[9].replace(',',''))

    with open(f'{inputdir}/{sample}/{sample}.kk.ra.xls',encoding='gbk') as f:
        outbook = Workbook()
        outbook.create_sheet(title='数据列表', index=0)
        os = outbook['数据列表']
        os.append(['D','G','S','species_zn','NC'])
        f.readline()
        for l in f:
            i = l.split('\t')
            if dealname(i[3]) in hmd or i[3].find('内标') > -1:
                continue
            else:
                if stat[sample] > 1_000_100:
                    reads = int(i[5]) * 1_000_100 / stat[sample]
                    if reads < 1:
                        continue
                    elif 1 <= reads <= 10:
                        print(f'{reads:.0f}')
                        os.append([i[0], i[2], i[3], i[4], f'{reads:.0f}'])
                    else:
                        os.append([i[0], i[2], i[3], i[4], f'{reads/10:.0f}'])
                else:
                    reads = int(i[5])
                    if reads < 1:
                        continue
                    elif 1 <= reads <= 10:
                        os.append([i[0], i[2], i[3], i[4], f'{reads:.0f}'])
                    else:
                        os.append([i[0], i[2], i[3], i[4], f'{reads/10:.0f}'])
    outbook.save(f'{outputdir}/NC数据列表.xlsx')

def getlist(_Microbe):
    hmd = []
    book = xlrd.open_workbook(_Microbe)
    Balfsheet = book.sheet_by_index(0)
    for i in range(1, Balfsheet.nrows):
        l = [str(j.value).strip() for j in Balfsheet.row(i)]
        hmd.append(l[0])
    return hmd

if __name__ == '__main__':
    inputdir = sys.argv[1]
    microbe = f'/data/softwares/mngs_scripts/auto/tag/NC-DNA_tag.xlsx'
    hmd = getlist(microbe)
    outputdir = sys.argv[2]
    dealkk(inputdir,hmd,outputdir)
